<template>
  <view class="cart-container">
    <!-- 购物车头部 -->
    <view class="cart-header">
      <text class="icon-back" @click="goBack">‹</text>
      <text class="title">购物车</text>
      <text class="edit-btn" @click="toggleEdit">
        {{ isEditing ? '完成' : '编辑' }}
      </text>
    </view>

    <!-- 空购物车 -->
    <view v-if="cartItems.length === 0" class="empty-cart">
      <image src="/static/empty-cart.png" class="empty-image" mode="aspectFit" />
      <text class="empty-text">购物车还是空的</text>
      <button class="go-shopping" @click="goToCategory">去逛逛</button>
    </view>

    <!-- 购物车列表 -->
    <scroll-view v-else scroll-y class="cart-list" :style="{ height: scrollViewHeight + 'px' }">
      <view 
        v-for="item in cartItems" 
        :key="item.id + '-' + (item.selectedSpec || '')"
        class="cart-item"
      >
        <view class="item-left">
          <checkbox 
            :checked="item.selected" 
            @click="toggleSelect(item.id, item.selectedSpec)"
            class="checkbox"
          />
          <image :src="item.cover" class="item-cover" mode="aspectFill" />
        </view>
        
        <view class="item-right">
          <text class="item-title">{{ item.title }}</text>
          <text class="item-spec" v-if="item.specName">规格: {{ item.specName }}</text>
          <text class="item-price">¥{{ item.price }}</text>
          
          <view class="item-actions">
            <view class="quantity-control">
              <text 
                class="btn minus" 
                @click="updateQuantity(item.id, item.selectedSpec, -1)"
                :class="{ disabled: item.quantity <= 1 }"
              >-</text>
              <text class="quantity">{{ item.quantity }}</text>
              <text 
                class="btn plus" 
                @click="updateQuantity(item.id, item.selectedSpec, 1)"
                :class="{ disabled: item.quantity >= item.stock }"
              >+</text>
            </view>
            
            <text 
              v-if="isEditing" 
              class="delete-btn"
              @click="removeItem(item.id, item.selectedSpec)"
            >删除</text>
          </view>
        </view>
      </view>
      
      <!-- 底部占位区域 -->
      <view class="bottom-placeholder" :style="{ height: placeholderHeight + 'px' }"></view>
    </scroll-view>

    <!-- 底部结算栏 -->
    <view v-if="cartItems.length > 0" class="cart-footer">
      <view class="footer-left">
        <checkbox 
          :checked="isAllSelected" 
          @click="toggleAllSelect"
          class="checkbox"
        />
        <text class="select-all-text">全选</text>
      </view>
      
      <view class="footer-right">
        <view class="total-price">
          <text class="total-amount">合计: ¥{{ totalPrice }}</text>
          <text class="total-quantity">共{{ selectedQuantity }}件</text>
        </view>
        <button 
          class="checkout-btn"
          :class="{ disabled: selectedCount === 0 }"
          @click="handleCheckout"
        >
          结算({{ selectedCount }})
        </button>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      isEditing: false,
      cartItems: [],
      scrollViewHeight: 0,
      placeholderHeight: 0,
      cartCount: 0
    }
  },
  computed: {
    isAllSelected() {
      return this.cartItems.length > 0 && this.cartItems.every(item => item.selected)
    },
    selectedCount() {
      return this.cartItems.filter(item => item.selected).length
    },
    selectedQuantity() {
      return this.cartItems
        .filter(item => item.selected)
        .reduce((sum, item) => sum + item.quantity, 0)
    },
    totalPrice() {
      return this.cartItems
        .filter(item => item.selected)
        .reduce((sum, item) => sum + (parseFloat(item.price) * item.quantity), 0)
        .toFixed(2)
    }
  },
  onLoad() {
    this.calcLayoutHeight()
    this.loadCartData()
    this.updateCartCount()
  },
  onShow() {
    this.loadCartData()
    this.updateCartBadge()
    this.updateCartCount()
  },
  onResize() {
    this.calcLayoutHeight()
  },
  methods: {
    // 计算布局高度
    calcLayoutHeight() {
      const systemInfo = uni.getSystemInfoSync()
      const windowHeight = systemInfo.windowHeight
      const headerHeight = 120 // 头部高度
      const footerHeight = 100 // 底部结算栏高度
      
      // 内容区域高度 = 窗口高度 - 头部高度 - 底部结算栏高度
      this.scrollViewHeight = windowHeight - headerHeight - footerHeight
      
      // 占位区域高度 = 安全区域底部间距
      this.placeholderHeight = systemInfo.safeAreaInsets?.bottom || 0
    },
    
    loadCartData() {
      this.cartItems = uni.getStorageSync('cart') || []
    },

    toggleEdit() {
      this.isEditing = !this.isEditing
    },

    toggleSelect(itemId, selectedSpec) {
      const item = this.cartItems.find(item => 
        item.id === itemId && item.selectedSpec === selectedSpec
      )
      if (item) {
        item.selected = !item.selected
        this.saveCart()
      }
    },

    toggleAllSelect() {
      const newState = !this.isAllSelected
      this.cartItems.forEach(item => {
        item.selected = newState
      })
      this.saveCart()
    },

    updateQuantity(itemId, selectedSpec, change) {
      const item = this.cartItems.find(item => 
        item.id === itemId && item.selectedSpec === selectedSpec
      )
      if (item) {
        const newQuantity = item.quantity + change
        if (newQuantity >= 1 && newQuantity <= item.stock) {
          item.quantity = newQuantity
          this.saveCart()
          this.updateCartBadge()
          this.updateCartCount()
        }
      }
    },

    removeItem(itemId, selectedSpec) {
      uni.showModal({
        title: '提示',
        content: '确定要删除这个商品吗？',
        success: (res) => {
          if (res.confirm) {
            this.cartItems = this.cartItems.filter(item => 
              !(item.id === itemId && item.selectedSpec === selectedSpec)
            )
            this.saveCart()
            this.updateCartBadge()
            this.updateCartCount()
            uni.showToast({ title: '删除成功', icon: 'success' })
          }
        }
      })
    },

    saveCart() {
      uni.setStorageSync('cart', this.cartItems)
    },

    updateCartBadge() {
      const totalQuantity = this.cartItems.reduce((sum, item) => sum + item.quantity, 0)
      if (totalQuantity > 0) {
        uni.setTabBarBadge({
          index: 2, // 购物车在tabbar的索引位置
          text: totalQuantity > 99 ? '99+' : totalQuantity.toString()
        })
      } else {
        uni.removeTabBarBadge({ index: 2 })
      }
    },

    updateCartCount() {
      this.cartCount = this.cartItems.reduce((sum, item) => sum + item.quantity, 0)
    },

    handleCheckout() {
      if (this.selectedCount === 0) {
        uni.showToast({ title: '请选择要结算的商品', icon: 'none' })
        return
      }
      
      const selectedItems = this.cartItems.filter(item => item.selected)
      uni.navigateTo({
        url: '/pages/order/confirm?items=' + encodeURIComponent(JSON.stringify(selectedItems))
      })
    },

    goToCategory() {
      uni.switchTab({ 
        url: '/pages/category/category' 
      })
    },

    goBack() {
      uni.navigateBack()
    }
  }
}
</script>

<style lang="scss" scoped>
.cart-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  background: #fff;
  border-bottom: 1rpx solid #eee;
  height: 120rpx;
  box-sizing: border-box;
  position: relative;
}

.icon-back {
  font-size: 48rpx;
  color: #333;
  position: absolute;
  left: 30rpx;
  top: 50%;
  transform: translateY(-50%);
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

.edit-btn {
  color: #007AFF;
  font-size: 28rpx;
  position: absolute;
  right: 30rpx;
  top: 50%;
  transform: translateY(-50%);
}

.empty-cart {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding-bottom: 100rpx;
}

.empty-image {
  width: 300rpx;
  height: 300rpx;
  margin-bottom: 40rpx;
  opacity: 0.6;
}

.empty-text {
  font-size: 32rpx;
  color: #666;
  margin-bottom: 40rpx;
}

.go-shopping {
  background: #007AFF;
  color: #fff;
  width: 200rpx;
  height: 70rpx;
  line-height: 70rpx;
  border-radius: 35rpx;
  font-size: 28rpx;
  border: none;
}

.cart-list {
  flex: 1;
  padding: 20rpx;
}

.cart-item {
  display: flex;
  background: #fff;
  margin-bottom: 20rpx;
  padding: 20rpx;
  border-radius: 10rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.item-left {
  display: flex;
  align-items: center;
  margin-right: 20rpx;
}

.checkbox {
  margin-right: 20rpx;
}

.item-cover {
  width: 120rpx;
  height: 160rpx;
  border-radius: 5rpx;
  display: block;
}

.item-right {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.item-title {
  font-size: 28rpx;
  margin-bottom: 10rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  color: #333;
  font-weight: 600;
}

.item-spec {
  font-size: 24rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.item-price {
  color: #ff6b6b;
  font-weight: bold;
  font-size: 32rpx;
  margin-bottom: 20rpx;
}

.item-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.quantity-control {
  display: flex;
  align-items: center;
  border: 1rpx solid #ddd;
  border-radius: 20rpx;
  overflow: hidden;
}

.btn {
  width: 60rpx;
  height: 50rpx;
  text-align: center;
  line-height: 50rpx;
  background: #f8f8f8;
  font-size: 28rpx;
  color: #333;
}

.btn.disabled {
  color: #ccc;
  background: #f0f0f0;
}

.quantity {
  width: 80rpx;
  text-align: center;
  font-size: 28rpx;
  color: #333;
}

.delete-btn {
  color: #ff6b6b;
  font-size: 26rpx;
  padding: 10rpx 20rpx;
  border: 1rpx solid #ff6b6b;
  border-radius: 20rpx;
}

.cart-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background: #fff;
  border-top: 1rpx solid #eee;
  height: 100rpx;
  box-sizing: border-box;
}

.footer-left {
  display: flex;
  align-items: center;
}

.select-all-text {
  font-size: 28rpx;
  color: #333;
  margin-left: 10rpx;
}

.footer-right {
  display: flex;
  align-items: center;
}

.total-price {
  text-align: right;
  margin-right: 20rpx;
}

.total-amount {
  display: block;
  font-size: 32rpx;
  color: #ff6b6b;
  font-weight: bold;
  margin-bottom: 5rpx;
}

.total-quantity {
  display: block;
  font-size: 24rpx;
  color: #666;
}

.checkout-btn {
  background: #ff6b6b;
  color: #fff;
  width: 200rpx;
  height: 70rpx;
  line-height: 70rpx;
  border-radius: 35rpx;
  font-size: 28rpx;
  border: none;
  
  &.disabled {
    background: #ccc;
  }
}

.bottom-placeholder {
  width: 100%;
}
</style>